package com.admission.service;

import java.io.File;
import java.io.IOException;
import java.util.List;

import org.apache.commons.lang.xwork.StringUtils;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.struts2.ServletActionContext;
import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import org.springside.modules.orm.Page;
import org.springside.modules.orm.PropertyFilter;
import org.xml.sax.SAXException;

import com.admission.dao.EnrollDetailDao;
import com.admission.model.EnrollDetail;
import com.admission.util.ArrayUtils;
import com.admission.util.DeleteFile;
import com.admission.util.EnrollUtils;
import com.admission.util.ExcelUtils;
import com.admission.util.FileFilter;
import com.admission.util.StaticEnroll;
import com.admission.util.XmlUtils;

@Repository
@Transactional
public class EnrollDetailManager {
	private EnrollDetailDao enrollDetailDao;
	private StaticEnroll staticEnroll;
	private ArrayUtils arrayUtils;

	public Page<EnrollDetail> getPage(Page<EnrollDetail> page) {
		return enrollDetailDao.getAll(page);
	}

	public Page<EnrollDetail> getPageByFilter(Page<EnrollDetail> page,
			List<PropertyFilter> filters) {
		return enrollDetailDao.findPage(page, filters);
	}

	public void createXml() {
		Page<EnrollDetail> enrollDetail = new Page<EnrollDetail>(8);
		String path = ServletActionContext.getServletContext().getRealPath(
				"/WEB-INF");
		path += "/other/mainpage-enroll-detail.xml";
		getTitleList(enrollDetail);
		XmlUtils.create(enrollDetail.getResult(), path);
	}

	/**
	 * 保存招生计划，同时生成图片，删除excel picPath为图片存放的目录
	 * 
	 * @throws Exception
	 */
	public void save(String excelPath) throws Exception {
		Workbook workbook = ExcelUtils.getCommonWorkbook(excelPath);

		Sheet sheet = workbook.getSheetAt(0);
		for (int j = 1; j <= sheet.getLastRowNum(); j++) {
			EnrollDetail rd = new EnrollDetail();

			Row row1 = sheet.getRow(j);
			rd.setYear(EnrollUtils.getCellFormatValue(row1.getCell(0)));
			rd.setProvince((String) arrayUtils.getKey(
					arrayUtils.getProvinceMap(),
					EnrollUtils.getCellFormatValue(row1.getCell(1))));
			rd.setType((String) arrayUtils.getKey(arrayUtils.getType(),
					EnrollUtils.getCellFormatValue(row1.getCell(2))));
			if (StringUtils.isEmpty(rd.getProvince())) {
				throw new Exception("招生计划表格第" + (j + 1) + "行的省份有错误，招生计划提交失败");
			}
			if (StringUtils.isEmpty(rd.getType())) {
				throw new Exception("招生计划表格第" + (j + 1) + "行的类型有错误，招生计划提交失败");
			}
			rd.setAcademy(EnrollUtils.getCellFormatValue(row1.getCell(3)));
			rd.setMajor(EnrollUtils.getCellFormatValue(row1.getCell(4)));
			rd.setEnrollNum(EnrollUtils.getCellFormatValue(row1.getCell(5)));
			rd.setBatch(EnrollUtils.getCellFormatValue(row1.getCell(6)));
			rd.setCampus(EnrollUtils.getCellFormatValue(row1.getCell(7)));
			rd.setContent(EnrollUtils.getCellFormatValue(row1.getCell(8)));

			enrollDetailDao.save(rd);
		}
		DeleteFile.delete(excelPath);
		try {
			staticEnroll.createHtmlForEnrollDetail();
		} catch (Exception e) {
			throw new Exception("招生计划静态页面生成失败，可能数据库中存在不合法字段，具体情况，请联系开发人员调试"
					+ e.toString());
		}
	}

	/**
	 * 获取年份，省份，类型的组合 ,前8条
	 * 
	 * @param page
	 * @return
	 */
	public Page<EnrollDetail> getTitleList(Page<EnrollDetail> page) {
		List<EnrollDetail> l = enrollDetailDao
				.find("from EnrollDetail group by year,province,type order by year desc ");
		if (page.getPageSize() * page.getPageNo() > l.size()) {
			page.setResult(l.subList(page.getPageSize()
					* (page.getPageNo() - 1), l.size()));
		} else
			page.setResult(l.subList(page.getPageSize()
					* (page.getPageNo() - 1),
					page.getPageSize() * page.getPageNo()));
		page.setTotalCount(l.size());
		return page;
	}

	public EnrollDetail getById(String id) {
		return enrollDetailDao.findUniqueBy("id", id);
	}

	public void delete(String path, String year, String province, String type)
			throws IOException, IllegalArgumentException, SAXException,
			IllegalAccessException {
		Criterion criterions = Restrictions.eq("year", year);
		Criterion criterions1 = Restrictions.eq("province", province);
		Criterion criterions2 = Restrictions.eq("type", type);
		List<EnrollDetail> l = null;
		if (StringUtils.isEmpty(province) || StringUtils.isEmpty(type)) {
			l = enrollDetailDao.find(criterions);
		} else {
			l = enrollDetailDao.find(criterions, criterions1, criterions2);
		}

		for (EnrollDetail enrollDetail : l) {
			enrollDetailDao.delete(enrollDetail);
		}
		File f = new File(path);
		// 删除静态网页
		String regx = "enroll-detail-" + year + "-" + province + "-" + type
				+ ".*";
		File[] s = f.listFiles(new FileFilter(regx));
		for (File file : s) {
			DeleteFile.deleteByFile(file);
		}
		staticEnroll.createHtmlForEnrollDetail();
	}

	public List<String> getYears() {
		return enrollDetailDao
				.find("select year from EnrollDetail group by year");
	}

	public List<String> yearList() {
		return enrollDetailDao
				.find("select distinct rd.year from EnrollDetail rd order by rd.year desc");
	}

	public List<String> typeList() {
		return enrollDetailDao
				.find("select distinct rd.type from EnrollDetail rd");
	}

	public List<String> provinceList() {
		return enrollDetailDao
				.find("select distinct rd.province from EnrollDetail rd");
	}

	public void setStaticEnroll(StaticEnroll staticEnroll) {
		this.staticEnroll = staticEnroll;
	}

	@Autowired
	public void setEnrollDetailDao(EnrollDetailDao enrollDetailDao) {
		this.enrollDetailDao = enrollDetailDao;
	}

	@Autowired
	public void setArrayUtils(ArrayUtils arrayUtils) {
		this.arrayUtils = arrayUtils;
	}

}
